<template>
  <div class="wrapper" style="position: absolute; z-index: 200;top: 14px;width: auto">
    <div class="selectModelType" >
      <div class="tip"><p>功能面板 | 地图量测</p></div>
      <el-button type="primary" size="mini" plain @click="SetMode('drawLine')">距离</el-button>
      <el-button type="primary" size="mini" plain @click="SetMode('drawPloy')">面积</el-button>
      <el-button type="danger" size="mini" plain @click="clearDrawingBoard()">清除</el-button>
    </div>



  </div>
</template>

<script>
  // import myViewer from "../cesiumViewer";
  // import {measureUtils} from "../../script/measureUtils"
  // import {gisStr,gisNum,funct1,funct2} from "../../script/test"
  export default {
    name: "measureOld",
    data(){
      return{
        tempPoints:[],
        tempEntities:[],
        handler:null,
        earthRadiusMeters:6371000.0,
        radiansPerDegree:Math.PI / 180.0,
        degreesPerRadian:180.0 / Math.PI,
        scene:null,
        beginSceneMode:null,

      }
    },
    components:{
      // myViewer
    },
    mounted() {
      this.scene = viewer.scene;
      viewer.camera.flyTo({
        destination:Cesium.Cartesian3.fromDegrees(113.524,34.819,5300),
        orientation: {
          heading:Cesium.Math.toRadians(360),
          pitch:Cesium.Math.toRadians(-90),
          roll: Cesium.Math.toRadians(0), //默认值8
        },
      })
      this.beginSceneMode = viewer.scene.mode
      viewer.scene.mode = Cesium.SceneMode.SCENE2D
    },
    methods:{
      clearEffects() {
        if (this.handler != null) {
          try{
            this.handler.destroy();
          }catch (e) {
          }


        }
      },

      //设置各种操作模式
      SetMode(mode) {
        if (mode == "drawPloy") {
          this.tempPoints = [];
          this.handler = new Cesium.ScreenSpaceEventHandler(this.scene.canvas);
          this.handler.setInputAction( (click) => {
            let cartesian = viewer.camera.pickEllipsoid(click.position, this.scene.globe.ellipsoid);
            if (cartesian) {
              let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
              let longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
              let latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
              this.tempPoints.push({lon: longitudeString, lat: latitudeString});
              let tempLength = this.tempPoints.length;
              this.drawPoint(this.tempPoints[this.tempPoints.length - 1]);
              if (tempLength > 1) {
                this.drawLine(this.tempPoints[this.tempPoints.length - 2], this.tempPoints[this.tempPoints.length - 1], true);
              }
            }
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

          this.handler.setInputAction((click) => {
            let cartesian = viewer.camera.pickEllipsoid(click.position, this.scene.globe.ellipsoid);
            if (cartesian) {
              let tempLength = this.tempPoints.length;
              if (tempLength < 3) {
                alert('请选择3个以上的点再执行闭合操作命令');
              } else {
                this.drawLine(this.tempPoints[0], this.tempPoints[this.tempPoints.length - 1], true);
                this.drawPoly(this.tempPoints);

                let ent =
                  viewer.entities.add({
                    position: Cesium.Cartesian3.fromDegrees(((this.tempPoints[0].lon + (this.tempPoints[this.tempPoints.length - 1].lon + this.tempPoints[this.tempPoints.length - 2].lon) / 2) / 2),
                      ((this.tempPoints[0].lat + (this.tempPoints[this.tempPoints.length - 1].lat + this.tempPoints[this.tempPoints.length - 2].lat) / 2) / 2)),
                    label: {
                      text: this.SphericalPolygonAreaMeters(this.tempPoints).toFixed(1) + '㎡',
                      font: '22px Helvetica',
                      fillColor: Cesium.Color.BLACK
                    }
                  });
                this.tempEntities.push(ent);
                this.tempPoints = [];
                this.clearEffects();
              }

            }
          }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        } else if ("drawLine" == mode) {
          this.tempPoints = [];
          this.handler = new Cesium.ScreenSpaceEventHandler(this.scene.canvas);//处理用户输入事件
          this.handler.setInputAction( (click) => {
            let cartesian = viewer.camera.pickEllipsoid(click.position, this.scene.globe.ellipsoid);//返回点击位置的坐标
            if (cartesian) {
              let cartographic = Cesium.Cartographic.fromCartesian(cartesian);//笛卡尔转弧度，笛卡尔：直角坐标
              let longitudeString = Cesium.Math.toDegrees(cartographic.longitude);//弧度转经纬度，弧度：球心坐标
              let latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
              this.tempPoints.push({lon: longitudeString, lat: latitudeString});
              let tempLength = this.tempPoints.length;
              this.drawPoint(this.tempPoints[this.tempPoints.length - 1]);//调用函数画点
              if (tempLength > 1) {//调用函数画线
                this.drawLine(this.tempPoints[this.tempPoints.length - 2], this.tempPoints[this.tempPoints.length - 1], true);
              }
            }
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
          this.handler.setInputAction( (click) => {
            this.tempPoints = [];
            this.clearEffects();
          }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        }
      },

      drawPoint(point) {//点击之后的小圆点
        let entity =
          viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(point.lon, point.lat),
            label: {
              text: '',
              font: '22px Helvetica'
            },
            point: {
              pixelSize: 10,
              color: Cesium.Color.CHARTREUSE
            }
          });
        this.tempEntities.push(entity);
      },

      drawLine(point1, point2, showDistance) {
        let entity =
          viewer.entities.add({
            polyline: {
              positions: [Cesium.Cartesian3.fromDegrees(point1.lon, point1.lat), Cesium.Cartesian3.fromDegrees(point2.lon, point2.lat)],
              width: 10.0,
              material: new Cesium.PolylineGlowMaterialProperty({
                color: Cesium.Color.CHARTREUSE.withAlpha(.5)
              })
            }
          });
        this.tempEntities.push(entity);
        if (showDistance) {
          let w = Math.abs(point1.lon - point2.lon);
          let h = Math.abs(point1.lat - point2.lat);
          let offsetV = w >= h ? 0.0005 : 0;
          let offsetH = w < h ? 0.001 : 0;
          let distance = this.getFlatternDistance(point1.lat, point1.lon, point2.lat, point2.lon);//计算两个经纬度距离
          entity =
            viewer.entities.add({
              position: Cesium.Cartesian3.fromDegrees(((point1.lon + point2.lon) / 2) + offsetH,
                ((point1.lat + point2.lat) / 2) + offsetV),
              label: {
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                text: distance.toFixed(1) + 'm',
                font: '22px Helvetica',
                fillColor: Cesium.Color.WHITE
              }
            });
          this.tempEntities.push(entity);
        }
      },

      drawPoly(points) {
        let pArray = [];
        for (let i = 0; i < points.length; i++) {
          pArray.push(points[i].lon);
          pArray.push(points[i].lat);
        }
        let entity =
          viewer.entities.add({
            polygon: {
              hierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(pArray)),
              material: Cesium.Color.CHARTREUSE.withAlpha(.5)
            }
          });
        this.tempEntities.push(entity);
      },

      //计算两点间距离
      getFlatternDistance(lat1, lng1, lat2, lng2) {
        let EARTH_RADIUS = 6378137.0;    //椭球的长半径，单位M
        let PI = Math.PI;

        function getRad(d) {
          return d * PI / 180.0;
        }

        let f = getRad((lat1 + lat2) / 2);
        let g = getRad((lat1 - lat2) / 2);
        let l = getRad((lng1 - lng2) / 2);

        let sg = Math.sin(g);
        let sl = Math.sin(l);
        let sf = Math.sin(f);

        let s, c, w, r, d, h1, h2;
        let a = EARTH_RADIUS;
        let fl = 1 / 298.257;

        sg = sg * sg;
        sl = sl * sl;
        sf = sf * sf;

        s = sg * (1 - sl) + (1 - sf) * sl;
        c = (1 - sg) * (1 - sl) + sf * sl;

        w = Math.atan(Math.sqrt(s / c));
        r = Math.sqrt(s * c) / w;
        d = 2 * w * a;
        h1 = (3 * r - 1) / 2 / c;
        h2 = (3 * r + 1) / 2 / s;

        return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
      },

      //计算多边形面积
      SphericalPolygonAreaMeters(points) {
        console.log("points:" + JSON.stringify(points))
        let totalAngle = 0;
        for (let i = 0; i < points.length; i++) {
          let j = (i + 1) % points.length;
          let k = (i + 2) % points.length;
          totalAngle += this.Angle(points[i], points[j], points[k]);
        }
        let planarTotalAngle = (points.length - 2) * 180.0;
        let sphericalExcess = totalAngle - planarTotalAngle;
        if (sphericalExcess > 420.0) {
          totalAngle = points.length * 360.0 - totalAngle;
          sphericalExcess = totalAngle - planarTotalAngle;
        } else if (sphericalExcess > 300.0 && sphericalExcess < 420.0) {
          sphericalExcess = Math.abs(360.0 - sphericalExcess);
        }
        return sphericalExcess * this.radiansPerDegree * this.earthRadiusMeters * this.earthRadiusMeters;
      },

      /*角度*/
      Angle(p1, p2, p3) {
        let bearing21 = this.Bearing(p2, p1);
        let bearing23 = this.Bearing(p2, p3);
        let angle = bearing21 - bearing23;
        if (angle < 0) {
          angle += 360;
        }
        return angle;
      },

      /*方向*/
      Bearing(from, to) {
        let lat1 = from.lat * this.radiansPerDegree;
        let lon1 = from.lon * this.radiansPerDegree;
        let lat2 = to.lat * this.radiansPerDegree;
        let lon2 = to.lon * this.radiansPerDegree;
        let angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
        if (angle < 0) {
          angle += Math.PI * 2.0;
        }
        angle = angle * this.degreesPerRadian;
        return angle;
      },

      /**
       * 清除地图痕迹
       */
      clearDrawingBoard() {
        let primitives = viewer.entities;
        for (let i = 0; i < this.tempEntities.length; i++) {
          primitives.remove(this.tempEntities[i]);
        }
        this.tempEntities = [];
        this.clearEffects();
      },


    },
    destroyed() {
      viewer.scene.mode = this.beginSceneMode
      mapBaseF.removeAllNtt()
    }
  }
</script>

<style scoped>

</style>
